// src/main/index.js
const { app, BrowserWindow } = require('electron')
const { join } = require('path')
const { electronApp, optimizer, is } = require('@electron-toolkit/utils')
const express = require('express')
const cors = require('cors')
const path = require('path')

// 获取正确的文件路径
const getAppPath = (relativePath) => {
  // 在开发环境中使用源代码目录
  if (process.env.NODE_ENV === 'development') {
    return path.join(__dirname, 'server', relativePath)
  }
  // 在生产环境中使用打包后的目录
  return path.join(process.resourcesPath, 'server', relativePath)
}

// 添加调试日志


// 导入服务器模块
const { connectDB, initDB } = require(path.join(process.cwd(), 'src/main/config/db.js'))
const userRoutes = require(path.join(process.cwd(), 'src/main/routes/user'))
const chatRoutes = require(path.join(process.cwd(), 'src/main/routes/chat'))
const dotenv = require('dotenv')
const { verifyEmailConfig } = require(path.join(process.cwd(), 'src/main/config/email.js'))

// 初始化 Express 服务器
function initServer() {
  dotenv.config()
  const server = express()
  const PORT = process.env.PORT || 3000

  // CORS 配置
  server.use(cors({
    origin: ['http://localhost:5173', 'app://*', 'http://localhost:3000'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization']
  }))

  server.use(express.json())

  // 添加调试日志
  server.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`)
    console.log('请求头:', req.headers)
    console.log('请求体:', req.body)
    next()
  })

  // 路由注册前的调试日志

  // 路由
  server.use('/api/user', userRoutes)
  server.use('/api/chat', chatRoutes)

  // 404 处理
  server.use((req, res, next) => {
    if (!res.headersSent) {
      console.log('未找到路由:', req.method, req.url)
      res.status(404).json({
        code: 404,
        message: '未找到请求的资源',
        success: false
      })
    }
  })

  // 错误处理中间件
  server.use((err, req, res, next) => {
    console.error('Server Error:', err.stack)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      success: false
    })
  })

  // 启动服务器
  const serverInstance = server.listen(PORT, async () => {

    try {
      await verifyEmailConfig()
      console.log('Email configuration verified')
    } catch (err) {
      console.error('Email configuration failed:', err)

    }

    try {
      await connectDB()
      console.log('Database connected')
      await initDB()
      console.log('Database initialized')

      // 迁移消息数据
      const Chat = require(path.join(process.cwd(), 'src/main/models/Chat.js'))
      await Chat.migrateMessagesSessionId()
    } catch (err) {
      console.error('Database initialization failed:', err)
      console.log('Continuing without database functionality...')
    }

    console.log('Server initialization completed (some features may be limited)')
  })

  serverInstance.on('error', (error) => {
    console.error('Server error:', error)
  })

  return serverInstance
}

function createWindow() {
  console.log('Creating main window...')
  const mainWindow = new BrowserWindow({
    width: 1290,
    height: 890,
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: true,
      webviewTag: true,
      // 启用远程模块
      enableRemoteModule: true,
      // 允许跨域
      allowRunningInsecureContent: true
    }
  })

  // 设置 CSP 头
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        // 删除任何现有的 CSP 头
        'content-security-policy': null,
        'Content-Security-Policy': [
          "default-src 'self' http://localhost:* ws://localhost:*; connect-src 'self' http://localhost:* ws://localhost:*; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: https:;"
        ]
      }
    })
  })

  // 设置额外的安全头
  mainWindow.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
    callback({
      requestHeaders: {
        ...details.requestHeaders,
        'Access-Control-Allow-Origin': '*'
      }
    })
  })

  // 开发环境下打开开发者工具
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools()
  }

  mainWindow.on('ready-to-show', () => {
    console.log('Main window is ready to show.')
    mainWindow.show()
  })

  // 加载应用
  if (process.env.VITE_DEV_SERVER_URL) {

    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
  } else {
    console.log('Loading file:', join(__dirname, '../renderer/index.html'))
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 添加错误处理
  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.error('Failed to load:', errorCode, errorDescription)
  })

  return mainWindow
}

// 应用启动
app.whenReady().then(() => {
  console.log('Electron app is ready')
  electronApp.setAppUserModelId('com.electron')

  // 初始化服务器
  const server = initServer()

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  // 应用退出时关闭服务器
  app.on('before-quit', () => {
    server.close()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
